package org.lanqiao.oa.utils;

import org.lanqiao.oa.mapper.ResultInfo;

import javax.validation.*;
import java.util.*;

public class CheckMapper {

    private CheckMapper(){}

    /**
     * 验证数据是否符合规范
     * @param mapper
     * @param <T>
     * @return
     */
    public static <T> boolean check(T mapper){
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> validate = validator.validate(mapper);
        for (ConstraintViolation<T> tConstraintViolation : validate) {
            System.out.println(tConstraintViolation.getMessage());
        }
        return validate.isEmpty();
    }

    public static <T> ResultInfo<Map<String,String>> check2(T mapper,Class...tClass){
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        //创建结果对象
        ResultInfo<Map<String,String>> result = new ResultInfo<>();
        //存放结果信息的集合
        Map<String,String> map = new HashMap<>();
        //获取错误信息
        Set<ConstraintViolation<T>> validate = validator.validate(mapper,tClass);
        for (ConstraintViolation<T> tConstraintViolation : validate) {
            String errorName = tConstraintViolation.getPropertyPath().toString();
            String errorMessage = tConstraintViolation.getMessage();
            map.put(errorName,errorMessage);
        }
        result.setT(map);
        result.setStatus(validate.isEmpty());

        return result;
    }


}
